package city.spring.modules.medicalstation.drug.controller;

import city.spring.modules.medicalstation.drug.entity.DrugEntity;
import city.spring.modules.medicalstation.drug.service.DrugService;
import city.spring.modules.medicalstation.drug.vo.DrugVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：医护站药品信息
 *
 * @author 谢金婷
 * @date 2020-08-14 11:07:57
 */
@RestController
@RequestMapping("/drug")
public class DrugController extends ApiController {
    private final DrugService drugService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<DrugEntity, ?>> entityOrderFields;

    public DrugController(DrugService drugService) {
        this.drugService = drugService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(DrugEntity::getId);
        entityOrderFields.add(DrugEntity::getName);
        entityOrderFields.add(DrugEntity::getCategory);
        entityOrderFields.add(DrugEntity::getSpecifications);
        entityOrderFields.add(DrugEntity::getUnit);
        entityOrderFields.add(DrugEntity::getUnitprice);
        entityOrderFields.add(DrugEntity::getDosageunit);
        entityOrderFields.add(DrugEntity::getSupplierId);
        entityOrderFields.add(DrugEntity::getManufacturer);
        entityOrderFields.add(DrugEntity::getUpperWarningvalue);
        entityOrderFields.add(DrugEntity::getLowerWarningvalue);
        entityOrderFields.add(DrugEntity::getType);
        entityOrderFields.add(DrugEntity::getDescription);
        entityOrderFields.add(DrugEntity::getGmtCreate);
        entityOrderFields.add(DrugEntity::getGmtModified);
        entityOrderFields.add(DrugEntity::getWarehousingquantity);
        entityOrderFields.add(DrugEntity::getDeliveryquantity);
        entityOrderFields.add(DrugEntity::getQuantity);
        entityOrderFields.add(DrugEntity::getStorehouseId);
        entityOrderFields.add(DrugEntity::getProductiondate);
        entityOrderFields.add(DrugEntity::getExpirationdate);
        entityOrderFields.add(DrugEntity::getIswarehouse);
        entityOrderFields.add(DrugEntity::getShelfId);
        entityOrderFields.add(DrugEntity::getWarehousingInventoryAmount);
        entityOrderFields.add(DrugEntity::getDeliveryInventoryAmount);
    }

    /**
     * 获取全部的 <strong>医护站药品信息</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DrugEntity entity) {
        LambdaQueryChainWrapper<DrugEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>医护站药品信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "name", direction = Sort.Direction.ASC), @SortDefault(sort = "sname", direction = Sort.Direction.ASC), @SortDefault(sort = "shelflevelname", direction = Sort.Direction.ASC), @SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, DrugVO entity) {
//        LambdaQueryChainWrapper<DrugEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<DrugEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
        QueryWrapper<? extends DrugEntity> queryWrapper = buildQuery(entity);
        return success(drugService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>医护站药品信息</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable Integer id) {
        QueryWrapper<DrugVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<DrugVO> records = drugService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(drugService.getById(id));
    }

    /**
     * 添加一个 <strong>医护站药品信息</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody DrugEntity entity) {
        drugService.saveDrug(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>医护站药品信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable Integer id, @RequestBody DrugEntity entity) {
        entity.setId(id);
        drugService.updateDrug(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>医护站药品信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable Integer id) {
        drugService.deleteDrug(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>医护站药品信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<Integer> ids) {
        drugService.deleteDrug(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DrugEntity> buildLambdaQuery(DrugEntity entity) {
        LambdaQueryChainWrapper<DrugEntity> lambdaQuery = drugService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, DrugEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getName()), DrugEntity::getName, entity.getName());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCategory()), DrugEntity::getCategory, entity.getCategory());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSpecifications()), DrugEntity::getSpecifications, entity.getSpecifications());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnit()), DrugEntity::getUnit, entity.getUnit());
        lambdaQuery.eq(entity.getUnitprice() != null, DrugEntity::getUnitprice, entity.getUnitprice());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDosageunit()), DrugEntity::getDosageunit, entity.getDosageunit());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSupplierId()), DrugEntity::getSupplierId, entity.getSupplierId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getManufacturer()), DrugEntity::getManufacturer, entity.getManufacturer());
        lambdaQuery.like(entity.getUpperWarningvalue() != null, DrugEntity::getUpperWarningvalue, entity.getUpperWarningvalue());
        lambdaQuery.like(entity.getLowerWarningvalue() != null, DrugEntity::getLowerWarningvalue, entity.getLowerWarningvalue());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getType()), DrugEntity::getType, entity.getType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDescription()), DrugEntity::getDescription, entity.getDescription());
        lambdaQuery.eq(entity.getGmtCreate() != null, DrugEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, DrugEntity::getGmtModified, entity.getGmtModified());
        lambdaQuery.eq(entity.getWarehousingquantity() != null, DrugEntity::getWarehousingquantity, entity.getWarehousingquantity());
        lambdaQuery.eq(entity.getDeliveryquantity() != null, DrugEntity::getDeliveryquantity, entity.getDeliveryquantity());
        lambdaQuery.eq(entity.getQuantity() != null, DrugEntity::getQuantity, entity.getQuantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), DrugEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.eq(entity.getProductiondate() != null, DrugEntity::getProductiondate, entity.getProductiondate());
        lambdaQuery.eq(entity.getExpirationdate() != null, DrugEntity::getExpirationdate, entity.getExpirationdate());
        lambdaQuery.eq(entity.getIswarehouse() != null, DrugEntity::getIswarehouse, entity.getIswarehouse());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getShelfId()), DrugEntity::getShelfId, entity.getShelfId());
        lambdaQuery.eq(entity.getWarehousingInventoryAmount() != null, DrugEntity::getWarehousingInventoryAmount, entity.getWarehousingInventoryAmount());
        lambdaQuery.eq(entity.getDeliveryInventoryAmount() != null, DrugEntity::getDeliveryInventoryAmount, entity.getDeliveryInventoryAmount());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<DrugEntity> buildQuery(DrugVO entity) {
        QueryWrapper<DrugEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCategory()), "t1.category", entity.getCategory());
        wrapper.like(StringUtils.isNotBlank(entity.getSpecifications()), "t1.specifications", entity.getSpecifications());
        wrapper.like(StringUtils.isNotBlank(entity.getUnit()), "t1.unit", entity.getUnit());
        wrapper.eq(entity.getUnitprice() != null, "t1.unitprice", entity.getUnitprice());
        wrapper.like(StringUtils.isNotBlank(entity.getDosageunit()), "t1.dosageunit", entity.getDosageunit());
        wrapper.like(StringUtils.isNotBlank(entity.getSupplierId()), "t1.supplier_id", entity.getSupplierId());
        wrapper.like(StringUtils.isNotBlank(entity.getSuppliername()), "t2.suppliername", entity.getSuppliername());
        wrapper.like(StringUtils.isNotBlank(entity.getManufacturer()), "t1.manufacturer", entity.getManufacturer());
        wrapper.like(entity.getUpperWarningvalue() != null, "t1.upper_warningvalue", entity.getUpperWarningvalue());
        wrapper.like(entity.getLowerWarningvalue() != null, "t1.lower_warningvalue", entity.getLowerWarningvalue());
        wrapper.like(StringUtils.isNotBlank(entity.getType()), "t1.type", entity.getType());
        wrapper.like(StringUtils.isNotBlank(entity.getDescription()), "t1.description", entity.getDescription());
        wrapper.eq(entity.getGmtCreate() != null, "t1.gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "t1.gmt_modified", entity.getGmtModified());
        wrapper.eq(entity.getWarehousingquantity() != null, "t1.warehousingquantity", entity.getWarehousingquantity());
        wrapper.eq(entity.getDeliveryquantity() != null, "t1.deliveryquantity", entity.getDeliveryquantity());
        wrapper.eq(entity.getQuantity() != null, "t1.quantity", entity.getQuantity());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t3.sname", entity.getSname());
        wrapper.eq(entity.getProductiondate() != null, "t1.productiondate", entity.getProductiondate());
        wrapper.eq(entity.getExpirationdate() != null, "t1.expirationdate", entity.getExpirationdate());
        wrapper.eq(entity.getIswarehouse() != null, "t1.iswarehouse", entity.getIswarehouse());
        wrapper.like(StringUtils.isNotBlank(entity.getShelfId()), "t1.shelf_id", entity.getShelfId());
        wrapper.like(StringUtils.isNotBlank(entity.getShelflevelname()), "t4.sname", entity.getShelflevelname());
        wrapper.eq(entity.getWarehousingInventoryAmount() != null, "t1.warehousing_inventory_amount", entity.getWarehousingInventoryAmount());
        wrapper.eq(entity.getDeliveryInventoryAmount() != null, "t1.delivery_inventory_amount", entity.getDeliveryInventoryAmount());
        return wrapper;
    }

}
